# -*- coding: utf-8 -*-
#
# Copyright 2009 Vanderbilt University
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#     http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 

"""

.. moduleauthor:: John Paulett <john.paulett -at- vanderbilt.edu>
"""
from __future__ import division
import logging

import hornet
from hornet.plugin import Plugin

logger = logging.getLogger(__name__)

class ReciprocityMeasure(Plugin):
    def notify(self, event):
        for period, graph in event.data.iteritems():
            self._netstats(period, graph)
        #self.plot(reciprocal.values())
        
    def _netstats(self, period, graph):
        reciprocal = {}
        ks = range(1, self.max_k+1)
        for k in ks:
            reciprocal[k] = self._reciprocity_at_k(graph, k)
            logger.debug('Completed level %i for %s' % (k, period))
        
        logger.debug('Finished ReciprocityMeasure for %s' % period)
        return reciprocal
        
    def _reciprocity_at_k(self, graph, k):
#        g = hornet.prune(graph, self.prune_filter, k)
#        logger.debug('Finished pruning')
#        reciprocal = len(hornet.reciprocity_pruning(g))
#        reciprocal = reciprocal / graph.size()

        def select(edge):
            return self.prune_filter(edge, k)
        reciprocal, size = hornet.reciprocity(graph, select)
        reciprocal = len(reciprocal) / len(size)

        return reciprocal
    
    def __calc_diff(self, data):
        diff = 1000 * numpy.diff(numpy.array(data))
        return numpy.log10(diff)
    
    def plot(self):
        pylab.subplot(211)
        pylab.plot(ks, 
                   [numpy.mean(x) for x in values])
        # FIXME to 95% CI
        xs, ys = pylab.poly_between(ks, 
                                    [numpy.mean(x)+numpy.std(x) for x in values],
                                    [numpy.mean(x)-numpy.std(x) for x in values])
        pylab.fill(xs, ys, facecolor='gray', alpha=0.25)

        pylab.subplot(212)        
        pylab.plot(ks[1:], self.__calc_diff([numpy.mean(x) for x in values]))
        pylab.show()
